package com.chen.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.chen.pojo.Provider;
import com.chen.service.bill.BillService;
import com.chen.service.provider.ProviderService;
import com.chen.tools.Constants;
import com.chen.tools.PageSupport;

@Controller
@RequestMapping("/provider")
public class ProviderController {
	private Logger logger = Logger.getLogger(ProviderController.class);
	@Resource(name="providerService")
	private ProviderService providerService;
	@Resource(name="billService")
	private BillService billService;
	
	@RequestMapping(value = "/providerlist")
	public String list(Model model, @RequestParam(value = "proName", required = false) String proName,
			@RequestParam(value = "proCode", required = false) String proCode,
			@RequestParam(value = "pageIndex", required = false) String pageIndex) throws Exception {
		logger.info("getProviderList --- > proName:" + proName);
		logger.info("getProviderList --- > proCode:" + proCode);
		logger.info("getProviderList --- > pageIndex:" + pageIndex);
//		int _queryUserRole = 0;
		List<Provider> providerList = null;
		// ����ҳ������
		int pageSize = Constants.pageSize;
		// ��ǰҳ��
		int currentPageNo = 1;
		if (proName == null) {
			proName = "";
		}
		/*if (proCode != null && !proCode.equals("")) {
			_queryUserRole = Integer.parseInt(proCode);
		}*/
		if (pageIndex != null) {
			currentPageNo = Integer.valueOf(pageIndex);
			return "redirect:/user/syserror.html";
		}
		// ������(��)
		int totalCount = providerService.getProvierCount(proName, proCode);
		// ��ҳ��
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		// ������ҳ��βҳ
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		providerList = providerService.getProviderList(proName, proCode, currentPageNo, pageSize);
		model.addAttribute("providerList", providerList);
		model.addAttribute("proName", proName);
		model.addAttribute("proCode", proCode);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		return "jsp/providerlist";
	}
	@RequestMapping(value="/syserror")
	public String sysError(){
		return "jsp/syserror";
	}
	
	@RequestMapping(value="/provideradd",method=RequestMethod.GET)
	public String addUser(@ModelAttribute("provider") Provider provider,Model model){
		model.addAttribute("provider", provider);
		return "jsp/provideradd";
	}
	/*@RequestMapping(value="/provideradd.html",method=RequestMethod.GET)
	public String addUser(Provider provider,Model model){
		model.addAttribute("provider", provider);
		return "provideradd2";
	}*/
		
	
	
	@RequestMapping(value="/provideraddsave",method=RequestMethod.POST)
	public String addUserSave(@RequestParam(value="attachs",required=false) MultipartFile[] attachs,Provider provider,HttpServletRequest request) throws Exception{
		String companyLicPicPath = null;
		String orgCodePicPath = null;
		String errorInfo = null;
		boolean flag = true;
		String path = request.getSession().getServletContext()
				.getRealPath("statics"+File.separator+"uploadfiles");
		for (int i = 0; i < attachs.length; i++) {
			MultipartFile attach = attachs[i];
			if(i == 0) {
				errorInfo = "uploadFileError";
			} else if (i == 1) {
				errorInfo = "uploadWpError";
			}
			String oldFileName = attach.getOriginalFilename();//Դ�ļ���
			String prefix = FilenameUtils.getExtension(oldFileName);//Դ�ļ���׺
			int filesize = 500000;
			if(attach.getSize() > filesize) {
				request.setAttribute(errorInfo, " * �ϴ���С���ó���500KB");
				flag = false;
			} else if (prefix.equalsIgnoreCase("jpg")
					|| prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("jpeg")
					|| prefix.equalsIgnoreCase("pneg")) {//�ϴ�ͼƬ��ʽ����ȷ
				String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000)+"_Personal.jpg";
				File targetFile = new File(path, fileName);
				if(!targetFile.exists()) {
					targetFile.mkdirs();
				}
				//����
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute(errorInfo, "�ϴ�ʧ��!");
					flag = false;
				}
				if(i == 0) {
					companyLicPicPath = fileName;
					// companyLicPicPath = path + File.separator + fileName;
				} else if (i == 1) {
					orgCodePicPath = fileName;
//					orgCodePicPath = path + File.separator + fileName;
				}
			} else {
				request.setAttribute(errorInfo, " * �ϴ�ͼƬ��ʽ����ȷ!");
			}
		}		
		if(flag){
			provider.setCreationDate(new Date());
			provider.setCompanyLicPicPath(companyLicPicPath);
			provider.setOrgCodePicPath(orgCodePicPath);
			if(providerService.add(provider)){
				return "redirect:/provider/providerlist";
			}
		}
		return "jsp/provideradd";
	}
	
	
	
	/*@RequestMapping(value="/provideraddsave.html",method=RequestMethod.POST)
	public String addUserSave(Provider provider,HttpSession session){
//		provider.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		provider.setCreationDate(new Date());
		if(providerService.add(provider)){
			return "redirect:/provider/providerlist.html";
		}
		return "provideradd";
	}*/
	@RequestMapping(value="/provideradd",method=RequestMethod.POST)
	public String addProviderSave(Provider provider,
									HttpSession session,Model model) throws Exception{
		/*if(bindingResult.hasErrors()){
			logger.debug("add user validated has error==============");
			return "provideradd2";
		}*/
		provider.setCreationDate(new Date());
		if(providerService.add(provider)){
			return "redirect:/provider/providerlist";
		}
		return "jsp/provideradd2";
	}
	
	@RequestMapping(value="/providermodify",method=RequestMethod.GET)
	public String providermodify(String id,Model model){
		Provider provider = new Provider();
		try {
			provider = providerService.getProviderById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("provider", provider);
		return "jsp/providermodify";
	}
	
	@RequestMapping(value="/providermodifysave",method=RequestMethod.POST)
	public String providerModifySave(Provider provider) throws Exception{
		provider.setCreationDate(new Date());
		if(providerService.modify(provider)){
			return "redirect:/provider/providerlist";
		}

		return "jsp/providermodify";
	}
	
	@RequestMapping(value="/providerview/{id}",method=RequestMethod.GET)
	public String providerview(@PathVariable String id,Model model) throws Exception{
		Provider provider = providerService.getProviderById(id);
		//�õ���ַ
		String companyLicPicPath = provider.getCompanyLicPicPath();
		//�õ���ַ
		String orgCodePicPath = provider.getOrgCodePicPath();
		//��ʲôλ�ý�ȡ
		int beginLicPicPath = 0;
		int beginCodePicPath = 0;
		//��βλ��
		int lastLicPicPath = 0;
		int lastCodePicPath = 0;
		//��ȡ�����ַ���
		String subCom = null;
		String subCode = null;
		if(companyLicPicPath != null && companyLicPicPath != ""){
			beginLicPicPath = companyLicPicPath.indexOf("uploadfiles");
			lastLicPicPath = companyLicPicPath.length();
			subCom = companyLicPicPath.substring(beginLicPicPath,lastLicPicPath);
			//���ַ�������ʵ���������
			provider.setCompanyLicPicPath(subCom);
		}
		if(orgCodePicPath != null && orgCodePicPath != ""){
			beginCodePicPath = orgCodePicPath.indexOf("uploadfiles");
			lastCodePicPath = orgCodePicPath.length();
			subCode = orgCodePicPath.substring(beginCodePicPath,lastCodePicPath);
			//���ַ�������ʵ���������
			provider.setOrgCodePicPath(subCode);
		}
		System.out.println(subCom);
		System.out.println(subCode);
		model.addAttribute("provider", provider);
		return "jsp/providerview";
	}
	@RequestMapping(value="/deleteProvider",method=RequestMethod.GET)
	@ResponseBody
	public Object deleteProvider(@RequestParam String proid){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			/*num = providerService.deleteProviderById(proid);
			if(num == 0){
				map.put("delResult", "true");
			} else if () {
				map.put("delResult", "false");
			}*/
			int count = billService.getBillCountByProviderId(proid);
			if(count > 0) {
				map.put("delResult", count);
			} else {
				int num = providerService.deleteProviderById(proid);
				if(num > 0) {
					map.put("delResult", "true");
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return JSONArray.toJSONString(map);
	}
}
